package io.noties.markwon.plugin.replacement

import io.noties.markwon.base.AbstractMarkwonPlugin
import org.commonmark.parser.Parser
import java.util.regex.Pattern

class ReplacementPlugin(private val replacementMap: Map<String, String>, private val  keysPattern: Pattern?) : AbstractMarkwonPlugin() {

    override fun configureParser(builder: Parser.Builder) {
        if (keysPattern != null) {
            builder.postProcessor(ReplacementPostProcessor(replacementMap, keysPattern))
        }
    }

    companion object{
        private fun getKeysPattern(replacementMap: Map<String, String>): Pattern? {
            val keys: Set<String> = HashSet(replacementMap.keys)
            return if (keys.isNotEmpty()) {
                val sb = StringBuilder()
                sb.append("(?<=(^|\\s))(")
                val iterator = keys.iterator()
                while (iterator.hasNext()) {
                    sb.append(Pattern.quote(iterator.next()))
                    if (iterator.hasNext()) {
                        sb.append('|')
                    }
                }
                sb.append(")(?=($|\\s))")
                Pattern.compile(sb.toString())
            } else {
                null
            }
        }

        fun create(replacementMap: Map<String, String>): ReplacementPlugin {
            return ReplacementPlugin(replacementMap, getKeysPattern(replacementMap))
        }
    }
}